import org.codehaus.groovy.grails.commons.ConfigurationHolder

/**
 * this controller is used to discover chemical compounds in the given parameter
 */
class DiscoveryController {

  //injected service
  DiscoveryService discoveryService
  DataExportService dataExportService = new DataExportService();

  def index = {

    println "\n\nsession.getAttribute :: ${session.getAttribute("query")}"
    if( session.getAttribute("query") != null )
    {
      return [query : session.getAttribute("query").toString()]
    }

  }
  /**
   * process a query and returns a map containning all the found chemical names
   */
  def process = {

    //logger is added automatically by grails
    log.debug "executing a query..."

    String query = ""

    if( params.query != null )
    {
       query = params.query
       session.setAttribute("query",query);
    }
    else
    {
      query = session.getAttribute("query").toString()
    }


    if( query == null || query.trim().length() == 0 )
    {
      flash.message = "Error! Query parameter is mandatory, Please Enter Query."
      redirect(action:"index")
    }


    //params are added automatically by grails
    assert (query != null)

    def limitConfidence = 0.5

    //if we don't have a confidence limit set we use the default
    //otherwise we assign on
    if (params.limitConfidence != null) {
      limitConfidence = params.limitConfidence
    }

    log.debug "params.query ::: "+query
 
    //contains the final result
    Collection<Map<Compound, ?>> result = discoveryService.process(query ,limitConfidence)

    assert result != null, "discovery service returned null, which can't be. Please fill a bug report!"


    if(params?.format && params.format != "html") //Export
       {

         println "======== In Upload =============";
         dataExportService.exportDiscover(result,response,params) 
       }else
        {
           //forward to the controller
            return [result: result]                  
        }

  } 
}